import threading

import uvicorn

from app.api_main import app
from common.config import settings
from common.exception_handlers import register_exception_handlers
from common.logger import create_logger
from mqtt.mqtt_main import main as mqtt_main

logger = create_logger(name="main", log_level=settings.log_level, log_file=settings.log_file, enable_file_logging=settings.enable_file_logging)


def start_fastapi():
	"""在子线程中启动 FastAPI"""
	try:
		logger.info("启动 FastAPI 子线程")
		uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info")
	except Exception as e:
		logger.error(f"FastAPI 启动失败: {e}")


if __name__ == "__main__":

	# 注册全局异常
	register_exception_handlers(app)

	# 启动 FastAPI 子线程
	fastapi_thread = threading.Thread(target=start_fastapi, daemon=True)
	fastapi_thread.start()

	# MQTT 消费者运行在主线程（避免 signal 报错）
	try:
		logger.info("启动 MQTT 消费者主线程")
		mqtt_main()
	except Exception as e:
		logger.error(f"MQTT 消费者启动失败: {e}")
